package com.yilin.gateway.core;

import com.google.gson.*;
import com.google.gson.internal.bind.ObjectTypeAdapter;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Map;


/**
 * JSON解析工具类
 */
public class JsonUtil {

    /**
     * JSON字符串转对象  根据TypeToken类型
     */
    public static <T> T jsonToObject(String jsonStr, TypeToken<T> typeToken) {
        if (jsonStr == null) return null;
        Object fromJson = getGson().fromJson(jsonStr, typeToken.getType());
        return (T) fromJson;
    }

    /**
     * 对象转JSON
     */
    public static <T> String objectToJson(T object) {
        if (object == null) return null;
        return getGson().toJson(object);
    }

    /**
     * MAP转对象
     */
    public static <T> T mapToObject(Map<String,Object> object,TypeToken<T> typeToken) {
        if (object == null) return null;
        return jsonToObject(objectToJson(object),typeToken);
    }

    public static Gson getGson() {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        try {
            Field factories = Gson.class.getDeclaredField("factories");
            factories.setAccessible(true);
            Object o = factories.get(gson);
            Class<?>[] declaredClasses = Collections.class.getDeclaredClasses();
            for (Class c : declaredClasses) {
                if ("java.util.Collections$UnmodifiableList".equals(c.getName())) {
                    Field listField = c.getDeclaredField("list");
                    listField.setAccessible(true);
                    List<TypeAdapterFactory> list = (List<TypeAdapterFactory>) listField.get(o);
                    int i = list.indexOf(ObjectTypeAdapter.FACTORY);
                    list.set(i, GsonTypeAdaptor.FACTORY);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return gson;
    }

    /**
     * 验证JSON格式
     * */
    public static boolean isJson(String json) {
        if (StringUtils.isBlank(json)) return false;
        try {
            new JsonParser().parse(json);
            return true;
        } catch (JsonParseException e) {
            return false;
        }
    }
}
